package com.wangyu.springsecuritydemo.service.impl;

import com.wangyu.springsecuritydemo.entity.primary.RoleEntity;
import com.wangyu.springsecuritydemo.repository.primary.RoleRepository;
import com.wangyu.springsecuritydemo.service.RoleService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.transaction.Transactional;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 权限服务层实现
 *
 * @author wangyu
 * @Date 2019/2/19 17:46
 * @Version 1.0
 **/
@Service("roleService")
public class RoleServiceImpl implements RoleService {

  @Autowired
  private RoleRepository roleRepository;

  @Override
  public List<RoleEntity> findByPermissionId(String permissionId) {
    Validate.notBlank(permissionId, "permissionId不能为空");

    Set<RoleEntity> roles = roleRepository.findByPermissionId(permissionId);
    if (roles == null || roles.isEmpty()) {
      return Collections.emptyList();
    }

    List<RoleEntity> roleList = new ArrayList<>(roles);
    return roleList;
  }

  @Override
  public List<RoleEntity> findByUserId(String userId) {
    Validate.notBlank(userId, "用户ID不能为空");

    Set<RoleEntity> roles = roleRepository.findByUserId(userId);
    if (roles == null || roles.isEmpty()) {
      return Collections.emptyList();
    }

    List<RoleEntity> roleList = new ArrayList<>(roles);
    return roleList;
  }

  @Override
  @Transactional
  public void insert(RoleEntity roleEntity) {
    Validate.notNull(roleEntity, "roleEntity对象不能为空");
    roleRepository.save(roleEntity);
  }
}
